package kt.com.bilin.coin.viewmodel

import com.bilin.coin.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kt.com.bilin.coin.api.*
import kt.com.bilin.coin.bean.AppConfigBean
import kt.com.bilin.coin.bean.AppVersionBean
import kt.com.bilin.coin.bean.UploadDataBean
import kt.com.bilin.coin.common.getString
import kt.com.bilin.coin.common.toastMessageLong
import kt.com.bilin.coin.ui.activity.MainActivity
import kt.com.bilin.coin.ui.dialog.HomeAlertDialog
import kt.com.bilin.coin.ui.dialog.LoadingDialog
import kt.com.bilin.coin.utils.ActivityManger
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

/**
 * 其他不绑定生命周期或者传递生命周期组件接口调用
 */
object BackgroundCommonApi {
    @JvmStatic
    fun <T> launchUI(
            block: suspend CoroutineScope.() -> T, apiObserver: ApiObserver<T>? = null, error: ((Throwable) -> Unit)? = null, complete: (() -> Unit)? = null,
    ): Job = ApiRequest(uiScope()).launchUI(block, error, complete, apiObserver)

    /**
     * 获取测试环境版本号
     */
    fun uploadFile(coroutineScope: CoroutineScope? = null, files: MutableList<UploadDataBean>, path: String, dialog: LoadingDialog? = null, callback: (data: String?) -> Unit) {
        if (files.isNotEmpty()) {
            ApiRequest(coroutineScope ?: uiScope()).launchUI({
                val data = API_SERVICE.upload(MultipartBody.Builder().apply {
                    val file = File(files[0].compressFile)
                    addFormDataPart("file", file.name, file.asRequestBody("multipart/form-data".toMediaType()))
                    addFormDataPart("path", path)
                }.build()).toData()
                if (data != null) {
                    callback(data)
                } else {
                    "上传失败".toastMessageLong()
                    callback(null)
                }
            }, error = {
                it.message.toastMessageLong()
                callback(null)
            }, apiObserver = dialog?.let { ApiObserver(dialog = dialog) })
        } else {
            "上传失败".toastMessageLong()
            callback(null)
        }
    }

    fun appVersion(callback: (appVersionBean: AppVersionBean?) -> Unit) {
        launchUI({ API_SERVICE.appVersion(R.string.version_name.getString()).toData() }, error = {
            callback.invoke(null)
        }, apiObserver = ApiObserver {
            callback.invoke(it)
        })
    }

    private var mAppConfigBean: AppConfigBean? = null
    fun appConfig(coroutineScope: CoroutineScope, callback: (appConfigBean: AppConfigBean?) -> Unit) {
        if (mAppConfigBean == null) {
            ApiRequest(coroutineScope).launchUI({
                mAppConfigBean = API_SERVICE.appConfig().toData()
                if (mAppConfigBean != null) {
                    callback(mAppConfigBean)
                } else {
                    "配置读取失败，请重试".toastMessageLong()
                    callback(null)
                }
            }, error = {
                it.message.toastMessageLong()
                callback(null)
            })
        } else {
            callback(mAppConfigBean)
        }
    }

    @JvmStatic
    fun notify(params: String = "") {
        launchUI({ API_SERVICE.notify().toData() }, ApiObserver {
            it?.run {
                if (content.isNotEmpty()) {
                    ActivityManger.getActivity(MainActivity::class.java)?.let {
                        HomeAlertDialog(it, title.ifEmpty { R.string.dialog_title.getString() }, content).show()
                    }
                }
            }
        })
    }
}
